package com.abvnet.project.water.project.service;

import com.abvnet.project.system.user.domain.User;
import com.abvnet.project.system.user.mapper.UserMapper;
import com.abvnet.project.water.project.domain.ProjectComment;
import com.abvnet.project.water.project.domain.ProjectPartner;
import com.abvnet.project.water.project.mapper.ProjectCommentMapper;
import com.abvnet.project.water.project.mapper.ProjectPartnerMapper;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目参与人员 服务层实现
 *
 * @author duj
 * @date 2019-07-19
 */
@Service
public class ProjectPartnerServiceImpl implements IProjectPartnerService {
    @Autowired
    private ProjectPartnerMapper projectPartnerMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ProjectCommentMapper projectCommentMapper;

    @Override
    public List<ProjectPartner> selectProjectPartnerByProjectId(Long projectId) {
        return projectPartnerMapper.selectProjectPartnerByProjectId(projectId);
    }

    @Override
    public List<User> selectUsersByProjectId(Long projectId) {
        List<User> userList = userMapper.selectProjectProgressUsers();
        userList.stream().filter(user -> projectPartnerMapper.selectProjectPartnerByProjectId(projectId).stream().anyMatch(p -> user.getUserId().longValue() == p.getUserId().longValue())).forEach(user -> user.setFlag(true));
        return userList;
    }

    @Override
    public int deleteProjectPartnerByProjectId(Long projectId) {
        return projectPartnerMapper.deleteProjectPartnerByProjectId(projectId);
    }

    /**
     * 修改项目参与人员
     *
     * @param projectPartner 项目参与人员信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateProjectPartner(ProjectPartner projectPartner) {
        projectPartnerMapper.deleteProjectPartnerByProjectId(projectPartner.getProjectId());
        int rows = projectPartnerMapper.batchProjectPartner(Arrays.stream(projectPartner.getUserIds()).map(p -> ProjectPartner.builder().userId(p).projectId(projectPartner.getProjectId()).build()).collect(Collectors.toList()));
        List<ProjectComment> list = Lists.newArrayList();
        Long[] fromUser = projectPartner.getUserIds();
        Long[] toUser = projectPartner.getUserIds();
        for (Long f : fromUser) {
            for (Long t : toUser) {
                if (f.longValue() != t.longValue()){
                    list.add(ProjectComment.builder().projectId(projectPartner.getProjectId()).commentFlag("N").commentUserId(f).userId(t).build());
                }
            }
        }
        projectCommentMapper.batchProjectComment(list);
        return rows;
    }
}